import 'dart:io';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:go_router/go_router.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/common/services/video_comment_service.dart';
import 'package:hinge/common/widgets/custom_dialog.dart';
import 'package:hinge/common/widgets/report_bottom_sheet.dart';
import 'package:hinge/store/index.dart';
import 'package:video_player/video_player.dart';

class VideoDetailPage extends StatefulWidget {
  final String videoId;

  const VideoDetailPage({Key? key, required this.videoId}) : super(key: key);

  @override
  State<VideoDetailPage> createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage> {
  late final PageController _pageController;
  final List<VideoDetailStore> _stores = [];
  List<VideoModel> _videos = [];
  int _currentIndex = 0;
  TextEditingController _commentController = TextEditingController();
  TextEditingController _popupCommentController =
      TextEditingController(); // 弹窗中的评论输入框控制器

  // 假评论数据
  final List<Map<String, String>> _comments = [
    {
      'avatar': 'assets/images/avatar1.png',
      'name': 'Somi',
      'content':
          "This Is Pure Magic! 😆 Every Smile, Every Tear, It's All So Incredibly Beautiful. Congratulations On Your Perfect Day!",
    },
    {
      'avatar': 'assets/images/avatar1.png',
      'name': 'Somi',
      'content':
          "This Is Pure Magic! 😆 Every Smile, Every Tear, It's All So Incredibly Beautiful. Congratulations On Your Perfect Day!",
    },
  ];

  @override
  void initState() {
    super.initState();
    // 初始化示例评论数据
    VideoCommentService.initSampleComments();
    _loadVideos();
  }

  Future<void> _loadVideos() async {
    // 获取所有视频
    final videos = VideoService.getVideoList();

    // 找到当前视频索引
    final int initialId = int.tryParse(widget.videoId) ?? 0;
    int initialIndex = videos.indexWhere((v) => v.id == initialId);
    if (initialIndex == -1) initialIndex = 0;

    setState(() {
      _videos = videos;
      _currentIndex = initialIndex;

      // 初始化页面控制器
      _pageController = PageController(initialPage: initialIndex);

      // 为每个视频创建一个store
      for (var i = 0; i < videos.length; i++) {
        _stores.add(VideoDetailStore());
      }

      // 预加载当前视频
      _stores[_currentIndex].loadVideoData(videos[_currentIndex].id.toString());

      // 预加载上下视频（如果存在）
      if (_currentIndex > 0) {
        _stores[_currentIndex - 1].loadVideoData(
          videos[_currentIndex - 1].id.toString(),
        );
      }
      if (_currentIndex < videos.length - 1) {
        _stores[_currentIndex + 1].loadVideoData(
          videos[_currentIndex + 1].id.toString(),
        );
      }
    });
  }

  void _onPageChanged(int index) {
    // 暂停当前视频
    if (_currentIndex != index && _currentIndex < _stores.length) {
      _stores[_currentIndex].videoController?.pause();
    }

    // 更新当前索引
    setState(() {
      _currentIndex = index;
    });

    // 预加载下一个视频（如果存在）
    if (index < _videos.length - 1 && index + 1 < _stores.length) {
      _stores[index + 1].loadVideoData(_videos[index + 1].id.toString());
    }

    // 预加载上一个视频（如果存在）
    if (index > 0 && index - 1 < _stores.length) {
      _stores[index - 1].loadVideoData(_videos[index - 1].id.toString());
    }

    // 播放当前视频
    if (index < _stores.length) {
      _stores[index].videoController?.play();
    }
  }

  // 检查用户是否已登录，如未登录则显示对话框
  Future<bool> _checkUserLogin({String action = 'perform this'}) async {
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog(action);
      return false;
    }
    return true;
  }

  // 显示登录提示对话框
  void _showLoginRequiredDialog(String action) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to login to $action action. Would you like to login now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        // 使用GoRouter导航到登录页面
        context.push('/login').then((_) {
          // 从登录页面返回后刷新数据
          _refreshAfterLogin();
        });
      },
    );
  }

  // 登录后刷新视频状态
  void _refreshAfterLogin() {
    // 检查组件是否还挂载
    if (!mounted) return;

    // 重新加载当前视频的状态
    if (_currentIndex < _stores.length) {
      _stores[_currentIndex].loadVideoData(
        _videos[_currentIndex].id.toString(),
      );
    }
    setState(() {});
  }

  // 处理视频点击
  void _handleVideoTap(int index) {
    if (_stores[index].videoController == null) return;

    if (_stores[index].isPlaying) {
      _stores[index].videoController!.pause();
    } else {
      _stores[index].videoController!.play();
    }
  }

  void showCommentSheet() async {
    // 确保初始化评论数据
    if (_currentIndex < _stores.length) {
      // 确保评论已加载
      _stores[_currentIndex].loadComments();
    }

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      isDismissible: true,
      enableDrag: true,
      builder: (context) {
        return DraggableScrollableSheet(
          initialChildSize: 0.7,
          minChildSize: 0.4,
          maxChildSize: 0.95,
          builder: (context, scrollController) {
            return Observer(
              builder: (_) {
                final store = _stores[_currentIndex];
                final commentCount = store.comments.length;
                // 检查实际登录状态
                final isLoggedIn =
                    UserService.getCurrentUser() != null &&
                    !UserService.isGuestUser();

                return Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(24),
                    ),
                  ),
                  child: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(
                          top: 16,
                          left: 20,
                          right: 20,
                          bottom: 8,
                        ),
                        child: Row(
                          children: [
                            Text(
                              '$commentCount comments',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ),
                            ),
                            Spacer(),
                            GestureDetector(
                              onTap: () => Navigator.of(context).pop(),
                              child: Icon(
                                Icons.close,
                                color: Colors.grey,
                                size: 22,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child:
                            store.isLoadingComments
                                ? Center(child: CircularProgressIndicator())
                                : store.comments.isEmpty
                                ? Center(child: Text('No comments yet'))
                                : ListView.builder(
                                  controller: scrollController,
                                  itemCount: store.comments.length,
                                  itemBuilder: (context, index) {
                                    final comment = store.comments[index];
                                    // 获取用户信息
                                    final user = UserService.getUserById(
                                      comment.userId,
                                    );

                                    return Padding(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 20,
                                        vertical: 8,
                                      ),
                                      child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          CircleAvatar(
                                            radius: 22,
                                            backgroundImage:
                                                user != null
                                                    ? AssetImage(user.avatar)
                                                    : null,
                                            child:
                                                user == null
                                                    ? Icon(
                                                      Icons.person,
                                                      color: Colors.white,
                                                    )
                                                    : null,
                                          ),
                                          SizedBox(width: 10),
                                          Expanded(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  children: [
                                                    Text(
                                                      user?.nickname ??
                                                          'Unknown',
                                                      style: TextStyle(
                                                        fontWeight:
                                                            FontWeight.w600,
                                                        color: Colors.indigo,
                                                      ),
                                                    ),
                                                    Spacer(),
                                                    GestureDetector(
                                                      onTap: () {
                                                        // 显示举报弹窗
                                                        showReportBottomSheet(
                                                          context,
                                                        );
                                                      },
                                                      child: Icon(
                                                        Icons.more_horiz,
                                                        color: Colors.grey,
                                                        size: 28.w,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                SizedBox(height: 4),
                                                Text(
                                                  comment.content,
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                    color: Colors.black87,
                                                    fontFamily: 'Inter',
                                                  ),
                                                ),
                                                SizedBox(height: 4),
                                                Text(
                                                  _formatTime(
                                                    comment.createdAt,
                                                  ),
                                                  style: TextStyle(
                                                    fontSize: 12,
                                                    color: Colors.grey,
                                                    fontFamily: 'Inter',
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    );
                                  },
                                ),
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(12, 8, 12, 22),
                        child: GestureDetector(
                          onTap: () {
                            // 未登录用户点击整个输入区域时，显示登录提示
                            if (!isLoggedIn) {
                              _showLoginRequiredDialog('comment on');
                            }
                          },
                          child: Stack(
                            alignment: Alignment.centerRight,
                            children: [
                              Container(
                                padding: EdgeInsets.only(right: 44.w),
                                height: 44.h,
                                decoration: BoxDecoration(
                                  color: Colors.black.withOpacity(0.3),
                                  borderRadius: BorderRadius.circular(22.w),
                                ),
                                child: TextField(
                                  controller: _popupCommentController,
                                  textAlignVertical: TextAlignVertical.center,
                                  enabled: isLoggedIn, // 仅登录用户可输入
                                  decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintText:
                                        isLoggedIn
                                            ? 'Say something'
                                            : 'Login to comment',
                                    hintStyle: TextStyle(
                                      color: Colors.white,
                                      fontSize: 15.sp,
                                      fontFamily: 'Inter',
                                    ),
                                    contentPadding: EdgeInsets.symmetric(
                                      horizontal: 16.w,
                                      vertical: 12.h,
                                    ),
                                  ),
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 15.sp,
                                    fontFamily: 'Inter',
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 16.w,
                                child: GestureDetector(
                                  onTap: () {
                                    if (isLoggedIn) {
                                      // 已登录用户 - 发送评论
                                      _addComment();
                                    } else {
                                      // 未登录用户 - 显示登录提示
                                      _showLoginRequiredDialog('comment on');
                                    }
                                  },
                                  child: Icon(
                                    isLoggedIn ? IconFont.send : Icons.login,
                                    color: Colors.white,
                                    size: 20.w,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  // 添加评论
  void _addComment() async {
    if (_popupCommentController.text.trim().isEmpty ||
        _currentIndex >= _stores.length)
      return;

    // 不再需要检查登录状态，因为只有已登录的用户才能点击发送按钮
    // 且已在showCommentSheet方法中处理了登录检查
    // if (!await _checkUserLogin(action: 'comment on')) return;

    final currentUser = UserService.getCurrentUser();
    if (currentUser != null) {
      final store = _stores[_currentIndex];
      await store.addComment(currentUser.id, _popupCommentController.text);
      _popupCommentController.clear();
    }
  }

  // 格式化时间显示
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()}y ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()}mo ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'just now';
    }
  }

  @override
  void dispose() {
    // 释放所有视频控制器
    for (var store in _stores) {
      store.dispose();
    }
    _commentController.dispose();
    _popupCommentController.dispose(); // 释放弹窗输入框控制器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏为透明
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,
      ),
    );

    return Scaffold(
      backgroundColor: Colors.black,
      extendBodyBehindAppBar: true,
      appBar: null,
      body:
          _stores.isEmpty
              ? Center(child: CircularProgressIndicator(color: Colors.white))
              : PageView.builder(
                controller: _pageController,
                scrollDirection: Axis.vertical,
                onPageChanged: _onPageChanged,
                itemCount: _videos.length,
                itemBuilder: (context, index) {
                  return _buildVideoPage(index);
                },
              ),
    );
  }

  Widget _buildVideoPage(int index) {
    final store = _stores[index];

    return Observer(
      builder: (_) {
        if (store.isLoading || store.video == null) {
          return Center(child: CircularProgressIndicator(color: Colors.white));
        }

        return Stack(
          fit: StackFit.expand,
          children: [
            // 视频播放器 (包装在GestureDetector中)
            GestureDetector(
              onTap: () => _handleVideoTap(index),
              child: Stack(
                alignment: Alignment.center,
                children: [
                  store.isVideoReady
                      ? VideoPlayer(store.videoController!)
                      : _buildCoverImage(store.video!),
                  // 播放/暂停图标 (仅在视频已初始化且暂停状态时显示)
                  if (store.isVideoReady && !store.isPlaying)
                    Icon(IconFont.play, color: Colors.white, size: 52.w),
                ],
              ),
            ),

            // 顶部渐变蒙层
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              height: 160.h,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.black.withOpacity(0.7),
                      Colors.black.withOpacity(0.3),
                      Colors.transparent,
                    ],
                  ),
                ),
              ),
            ),

            // 底部渐变蒙层
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              height: 280.h, // 调整高度以覆盖底部区域
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter,
                    colors: [
                      Colors.black.withOpacity(0.8),
                      Colors.black.withOpacity(0.6),
                      Colors.black.withOpacity(0.3),
                      Colors.transparent,
                    ],
                  ),
                ),
              ),
            ),

            // 顶部导航栏 - 自定义完全透明的导航栏
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: EdgeInsets.only(
                  top: MediaQuery.of(context).padding.top,
                  left: 8.w,
                  right: 8.w,
                ),
                child: Row(
                  children: [
                    IconButton(
                      icon: Icon(
                        IconFont.back,
                        color: Colors.white,
                        size: 28.w,
                      ),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                    SizedBox(width: 4.w),
                    Text(
                      'Details',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Spacer(), // 将举报按钮推到右侧
                    IconButton(
                      icon: Icon(
                        IconFont.report,
                        color: Colors.white,
                        size: 28.w,
                      ),
                      onPressed: () {
                        // 调用举报底部弹出框
                        showReportBottomSheet(context);
                      },
                    ),
                  ],
                ),
              ),
            ),

            // 播放按钮 (仅在视频未初始化时显示)
            if (!store.isVideoReady)
              Center(
                child: GestureDetector(
                  onTap: () {
                    store.videoController?.play();
                  },
                  child: Icon(
                    IconFont.play,
                    color: Colors.white.withOpacity(0.8),
                    size: 60.w,
                  ),
                ),
              ),

            // 右侧交互按钮
            Positioned(
              right: 20.w,
              bottom: 120.h,
              child: Column(
                children: [
                  // 收藏按钮
                  _buildActionButton(
                    icon: store.isCollected ? IconFont.likeFill : IconFont.like,
                    count: store.video!.collectCount.toString(),
                    isActive: store.isCollected,
                    onTap: () async {
                      // 检查用户登录状态
                      if (await _checkUserLogin(action: 'collect')) {
                        store.toggleCollect();
                      }
                    },
                  ),
                  SizedBox(height: 20.h),
                  // 点赞按钮
                  _buildActionButton(
                    icon: store.isLiked ? IconFont.goodFill : IconFont.good,
                    count: store.video!.likeCount.toString(),
                    isActive: store.isLiked,
                    onTap: () async {
                      // 检查用户登录状态
                      if (await _checkUserLogin(action: 'like')) {
                        store.toggleLike();
                      }
                    },
                  ),
                  SizedBox(height: 20.h),
                  // 评论按钮
                  _buildActionButton(
                    icon: IconFont.chat,
                    count: store.video!.commentCount.toString(),
                    onTap: () => showCommentSheet(),
                  ),
                ],
              ),
            ),

            // 底部视频描述
            Positioned(
              left: 20.w,
              right: 100.w, // 为右侧按钮留出空间
              bottom: 110.h, // 上移视频描述，给输入框留出空间
              child: Text(
                store.video!.description,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontFamily: "Inter",
                  fontWeight: FontWeight.w500,
                  height: 1.5,
                ),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ),

            // 底部输入框
            Positioned(
              left: 0,
              right: 0,
              bottom: 22.h,
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () => showCommentSheet(), // 无条件打开评论弹出框
                child: AbsorbPointer(
                  child: Container(
                    padding: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 20.h),
                    child: Stack(
                      alignment: Alignment.centerRight,
                      children: [
                        Container(
                          padding: EdgeInsets.only(right: 44.w),
                          height: 44.h,
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(22.w),
                          ),
                          child: TextField(
                            textAlignVertical: TextAlignVertical.center,
                            controller: _commentController,
                            enabled: false, // 底部输入框始终保持禁用，只作展示用
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: 'Add a comment...',
                              hintStyle: TextStyle(
                                fontSize: 15.sp,
                                color: Colors.white,
                                fontFamily: 'Inter',
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16.w,
                                vertical: 10.h,
                              ),
                            ),
                            style: TextStyle(
                              fontSize: 15.sp,
                              color: Colors.white,
                              fontFamily: 'Inter',
                            ),
                          ),
                        ),
                        Positioned(
                          right: 16.w,
                          child: GestureDetector(
                            onTap: showCommentSheet, // 同样无条件打开评论弹出框
                            child: Icon(
                              IconFont.send,
                              color: Colors.white,
                              size: 22.w,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),

            // 上下滑动提示
            // if (index == 0) // 第一个视频时显示向下滑动提示
            //   Positioned(
            //     bottom: 80.h,
            //     left: 0,
            //     right: 0,
            //     child: Center(
            //       child: Column(
            //         children: [
            //           Text(
            //             'Slide down to watch more videos.',
            //             style: TextStyle(
            //               color: Colors.white.withOpacity(0.7),
            //               fontSize: 12.sp,
            //               fontFamily: 'Inter',
            //               fontWeight: FontWeight.w400,
            //             ),
            //           ),
            //           SizedBox(height: 5.h),
            //           Icon(
            //             Icons.keyboard_arrow_down,
            //             color: Colors.white.withOpacity(0.7),
            //             size: 24.w,
            //           ),
            //         ],
            //       ),
            //     ),
            //   ),
          ],
        );
      },
    );
  }

  Widget _buildCoverImage(VideoModel video) {
    if (video.isCoverFile) {
      // 如果是文件路径，使用File读取图片
      return Image.file(
        File(video.coverUrl),
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
        errorBuilder: (context, error, stackTrace) {
          // 如果文件加载失败，显示默认图像
          return Image.asset(
            AssetsImages.strong1,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          );
        },
      );
    } else {
      // 否则按常规方式使用资源路径
      return Image.asset(
        video.coverUrl,
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
      );
    }
  }

  Widget _buildActionButton({
    required IconData icon,
    required String count,
    bool isActive = false,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          // 替换静态图标为动画图标
          AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            transitionBuilder: (child, animation) {
              return ScaleTransition(scale: animation, child: child);
            },
            child: Icon(
              icon,
              key: ValueKey<String>("icon_$isActive"),
              color: isActive ? Color(0xFFE7A7FF) : Colors.white,
              size: 32.w,
            ),
          ),
          SizedBox(height: 4.h),
          Text(
            count,
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp,
              fontWeight: FontWeight.w600,
              fontFamily: 'Inter',
            ),
          ),
        ],
      ),
    );
  }
}
